<?php

namespace app\store\model;

use app\common\model\User as UserModel;

use app\store\model\dealer\User as DealerUserModel;
use app\store\model\user\GradeLog as GradeLogModel;
use app\store\model\user\PointsLog as PointsLogModel;
use app\store\model\user\BalanceLog as BalanceLogModel;
use app\common\enum\user\balanceLog\Scene as SceneEnum;
use app\common\enum\user\grade\log\ChangeType as ChangeTypeEnum;
use app\common\library\helper;

/**
 * 用户模型
 * Class User
 * @package app\store\model
 */
class User extends UserModel
{
    /**
     * 获取当前用户总数
     * @param null $day
     * @return int|string
     * @throws \think\Exception
     */
    public function getUserTotal($day = null)
    {
        if (!is_null($day)) {
            $startTime = strtotime($day);
            $this->where('create_time', '>=', $startTime)
                ->where('create_time', '<', $startTime + 86400);
        }
        return $this->where('is_delete', '=', '0')->count();
    }

    /**
     * 获取用户列表
     * @param string $nickName 昵称
     * @param int $gender 性别
     * @param int $grade 会员等级
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($nickName = '', $gender = -1, $grade = null, $UID = 0, $sxkeyword='', $minmoney=0)
    {
        // 检索：微信昵称
        !empty($nickName) && $this->where('nickName', 'like', "%$nickName%");
		// 检索：姓名/手机/备注
		!empty($sxkeyword) && $this->where('true_name|true_mobile|user_remark', 'like', "%$sxkeyword%");
        // 检索：性别
        if ($gender !== '' && $gender > -1) {
            $this->where('gender', '=', (int)$gender);
        }
		// 根据uid检索
		if($UID>0){
			$this->where('user_id', '=', (int)$UID);
		}
        // 检索：会员等级
        $grade > 0 && $this->where('grade_id', '=', (int)$grade);
		$minmoney>0 && $this->where('balance', '>=', (int)$minmoney);
		$orderArr = ['create_time' => 'desc'];
		$minmoney>0 ? $orderArr = ['balance' => 'desc'] : '';
        // 获取用户列表
        return $this->with(['grade'])
            ->where('is_delete', '=', '0')
            ->order($orderArr)
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 删除用户
     * @return bool|mixed
     */
    public function setDelete()
    {
        // 判断是否为分销商
        if (DealerUserModel::isDealerUser($this['user_id'])) {
            $this->error = '当前用户为分销商，不可删除';
            return false;
        }
        return $this->transaction(function () {
            // 删除用户推荐关系
            (new DealerUserModel)->onDeleteReferee($this['user_id']);
            // 标记为已删除
            return $this->save(['is_delete' => 1]);
        });
    }

    /**
     * 用户充值
     * @param string $storeUserName 当前操作人用户名
     * @param int $source 充值类型
     * @param array $data post数据
     * @return bool
     */
    public function recharge($storeUserName, $source, $data)
    {
        if ($source == 0) {
            return $this->rechargeToBalance($storeUserName, $data['balance']);
        } elseif ($source == 1) {
            return $this->rechargeToPoints($storeUserName, $data['points']);
        }
        return false;
    }

    /**
     * 用户充值：余额
     * @param $storeUserName
     * @param $data
     * @return bool
     */
    private function rechargeToBalance($storeUserName, $data)
    {
        if (!isset($data['money']) || $data['money'] === '' || $data['money'] < 0) {
            $this->error = '冲减金额不能为空或小于0元';
            return false;
        }
		if (!isset($data['giftmoney']) || $data['giftmoney'] === '' || $data['giftmoney'] < 0) {
		    $this->error = '赠送金额不能为空或小于0元';
		    return false;
		}
		if(!isset($data['payType'])){
			$this->error = '请选择线下现场支付方式';
			return false;
		}
		if($data['giftmoney']==0 && $data['money']==0){
			$this->error = '冲减金额或赠送金额必需有一项大于零';
			return false;
		}
		
		// $this->error = $this['balance'].'测试到此处打断点'.$data['mode'];
		// return false;
		// 如果存在冲减金额，执行冲减操作，并

			// 判断充值方式，计算最终金额
			if ($data['mode'] === 'inc') {
				$diffMoney = $data['money'];
			} elseif ($data['mode'] === 'dec') {
				$diffMoney = -$data['money'];
			} else {
				// 如果是不充值，不减扣的操作，则设置为原始的余额
				$diffMoney = helper::bcsub($data['money'], $this['balance']);
			}
			// 更新记录
			$this->transaction(function () use ($storeUserName, $data, $diffMoney) {
				// 更新账户余额，如果存在赠送金额，则充值总额为充值金额加赠送金额
				if ($data['mode'] === 'inc') {
					$this->setInc('balance', $data['money']+$data['giftmoney']);
				}
				else{
					$this->setInc('balance', $diffMoney);
				}
				// 更新账户线下付款方式
				// $status = $this->save(['balance' => $data['grade_id']]);
				
				// 新增余额变动记录，实际统计中不统计赠送金额
				BalanceLogModel::add(SceneEnum::ADMIN, [
					'user_id' => $this['user_id'],
					'money' => $diffMoney,
					'pay_type' => $data['payType'],
					'giftmoney' => $data['giftmoney'],
					'remark' => $data['remark'],
				], [$storeUserName]);
			});

        return true;
    }

    /**
     * 用户充值：积分
     * @param $storeUserName
     * @param $data
     * @return bool
     */
    private function rechargeToPoints($storeUserName, $data)
    {
        if (!isset($data['value']) || $data['value'] === '' || $data['value'] < 0) {
            $this->error = '请输入正确的积分数量';
            return false;
        }
        // 判断充值方式，计算最终积分
        if ($data['mode'] === 'inc') {
            $diffMoney = $data['value'];
        } elseif ($data['mode'] === 'dec') {
            $diffMoney = -$data['value'];
        } else {
            $diffMoney = $data['value'] - $this['points'];
        }
        // 更新记录
        $this->transaction(function () use ($storeUserName, $data, $diffMoney) {
            // 更新账户积分
            $this->setInc('points', $diffMoney);
            // 新增积分变动记录
            PointsLogModel::add([
                'user_id' => $this['user_id'],
                'value' => $diffMoney,
                'describe' => "后台管理员 [{$storeUserName}] 操作",
                'remark' => $data['remark'],
            ]);
        });
        return true;
    }

    /**
     * 修改用户等级
     * @param $data
     * @return mixed
     */
    public function updateGrade($data)
    {
        // 变更前的等级id
        $oldGradeId = $this['grade_id'];
        return $this->transaction(function () use ($oldGradeId, $data) {
            // 更新用户的等级
            $status = $this->save(['grade_id' => $data['grade_id'],
			'true_name' => $data['true_name'],
			'true_mobile' => $data['true_mobile'],
			'user_remark' => $data['user_remark'],
			'gender' => $data['gender'],
			'address' => $data['address'],
			]);
            // 新增用户等级修改记录
            if ($status) {
                (new GradeLogModel)->record([
                    'user_id' => $this['user_id'],
                    'old_grade_id' => $oldGradeId,
                    'new_grade_id' => $data['grade_id'],
                    'change_type' => ChangeTypeEnum::ADMIN_USER,
                ]);
            }
            return $status !== false;
        });
    }

    /**
     * 消减用户的实际消费金额
     * @param $userId
     * @param $expendMoney
     * @return int|true
     * @throws \think\Exception
     */
    public function setDecUserExpend($userId, $expendMoney)
    {
        return $this->where(['user_id' => $userId])->setDec('expend_money', $expendMoney);
    }

}
